package com.sms.msger.msg.mytask.sms;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class TransactionCenter {
    private URL url;
    private HttpURLConnection urlconn;

    String inencoding;
    String outencoding;
    
    public TransactionCenter(String inencoding, String outencoding) {
        this.inencoding = inencoding;
        this.outencoding = outencoding;
    }
    
    public String connect(String params, String postUrl) throws Exception {
        BufferedReader br = null;
        String response = "", brLine = "";
        try {
            //params=URLEncoder.encode(params,"GB2312"); //use URLEncoder.encode for encode the params

            url = new URL(postUrl);
            urlconn = (HttpURLConnection) url.openConnection();
            urlconn.setRequestProperty("user-agent","mozilla/4.7 [en] (win98; i)");    //set request header 
            urlconn.setRequestProperty("X-Forwarded-For", "127.0.0.1");
            urlconn.setConnectTimeout(30000);
            urlconn.setReadTimeout(30000);
            urlconn.setRequestMethod("POST");     // request method, default GET
            urlconn.setUseCaches(false);    //Post can not user cache
            urlconn.setDoOutput(true);    //set output from urlconn
            urlconn.setDoInput(true);    //set input from urlconn
            OutputStream out = urlconn.getOutputStream();
            out.write(params.getBytes(outencoding));
            out.flush();
            out.close();    // output stream close,That's means need not to post data to this outputstream

            br = new BufferedReader(new InputStreamReader(urlconn.getInputStream(), inencoding));
            while((brLine = br.readLine())!=null)
                response =(new StringBuilder(String.valueOf(response))).append(brLine).toString();
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());
        } finally {
            try {
                if(br != null) {
                    br.close();
                }
            } catch (IOException e) {
                System.out.println("input stream close fail");
            }
            urlconn.disconnect();
        }
        return response;
    }

    public static void main(String[] args) {
        TransactionCenter tc = new TransactionCenter("GBK", "GBK");
//        String response = tc.connect("username=SONIC&password=888888&sms=HelloWorld&dest=13580576741","http://113.106.89.207/websms/admin/jkservicepl.jsp?");
//        System.out.println(response);
    }
}